using Microsoft.AspNetCore.Http;
using QingShan.Data.Constants;
using System;
using System.Data;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Runtime.InteropServices;

namespace QingShan.Utilities
{

#pragma warning disable CS1574 // XML 注释中有无法解析的 cref 特性
    /// <summary>
    /// web文件帮助类
    /// <para>当前存放路径为为<see cref="AppDomain.CurrentDomain.BaseDirectory"/></para>
    /// </summary>
    public class FileHelper
#pragma warning restore CS1574 // XML 注释中有无法解析的 cref 特性
    {
        /// <summary>
        /// 当前操作系统是否是Linux
        /// <para>在Linux中，如果一个项目的根目录为：/root</para>
        /// <para>string path = Path.Combine( Directory.GetCurrentDirectory(), "console\\Temp\\test.txt");</para>
        /// <para>那么path路径为如果写成`\root\console\Temp\test.txt`则`console\Temp\test.txt`是一个名为`console\temp\test`的txt文件。</para>
        /// <para>在Windows下路径应该这么写： C:\console\temp\test.txt 在Linux下则是这样的： /root/console/temp/test.txt</para>
        /// </summary>
        private readonly static bool IsLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux);

        /// <summary>
        /// web程序运行时目录
        /// </summary>

        private readonly static string _path = AppDomain.CurrentDomain.BaseDirectory;

        #region 检测指定目录是否存在
        /// <summary>
        /// 检测指定目录是否存在
        /// </summary>
        /// <param name="directoryPath">目录的绝对路径</param>
        /// <returns></returns>
        public static bool IsExistDirectory(string directoryPath)
        {
            return Directory.Exists(directoryPath);
        }
        #endregion

        #region 检测指定文件是否存在,如果存在返回true
        /// <summary>
        /// 检测指定文件是否存在,如果存在则返回true。
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>        
        public static bool IsExistFile(string filePath)
        {
            return File.Exists(filePath);
        }
        #endregion

        #region 获取指定目录中的文件列表
        /// <summary>
        /// 获取指定目录中所有文件列表
        /// </summary>
        /// <param name="directoryPath">指定目录的绝对路径</param>        
        public static string[] GetFileNames(string directoryPath)
        {
            //如果目录不存在，则抛出异常
            if (!IsExistDirectory(directoryPath))
            {
                throw new FileNotFoundException();
            }

            //获取文件列表
            return Directory.GetFiles(directoryPath);
        }
        #endregion

        #region 获取指定目录中所有子目录列表,若要搜索嵌套的子目录列表,请使用重载方法.
        /// <summary>
        /// 获取指定目录中所有子目录列表,若要搜索嵌套的子目录列表,请使用重载方法.
        /// </summary>
        /// <param name="directoryPath">指定目录的绝对路径</param>        
        public static string[] GetDirectories(string directoryPath)
        {
            try
            {

                if (IsLinux)
                {
                    directoryPath = directoryPath.Replace("\\", "/");
                }

                return Directory.GetDirectories(directoryPath);
            }
            catch (IOException ex)
            {
                throw;
            }
        }
        #endregion

        #region 获取指定目录及子目录中所有文件列表
        /// <summary>
        /// 获取指定目录及子目录中所有文件列表
        /// </summary>
        /// <param name="directoryPath">指定目录的绝对路径</param>
        /// <param name="searchPattern">模式字符串，"*"代表0或N个字符，"?"代表1个字符。
        /// 范例："Log*.xml"表示搜索所有以Log开头的Xml文件。</param>
        /// <param name="isSearchChild">是否搜索子目录</param>
        public static string[] GetFileNames(string directoryPath, string searchPattern, bool isSearchChild)
        {
            //如果目录不存在，则抛出异常
            if (!IsExistDirectory(directoryPath))
            {
                throw new FileNotFoundException();
            }

            try
            {
                if (IsLinux)
                {
                    directoryPath = directoryPath.Replace("\\", "/");
                }
                if (isSearchChild)
                {
                    return Directory.GetFiles(directoryPath, searchPattern, SearchOption.AllDirectories);
                }
                else
                {
                    return Directory.GetFiles(directoryPath, searchPattern, SearchOption.TopDirectoryOnly);
                }
            }
            catch (IOException ex)
            {
                throw;
            }
        }
        #endregion

        #region 检测指定目录是否为空
        /// <summary>
        /// 检测指定目录是否为空
        /// </summary>
        /// <param name="directoryPath">指定目录的绝对路径</param>        
        public static bool IsEmptyDirectory(string directoryPath)
        {
            try
            {
                if (IsLinux)
                {
                    directoryPath = directoryPath.Replace("\\", "/");
                }
                //判断是否存在文件
                string[] fileNames = GetFileNames(directoryPath);
                if (fileNames.Length > 0)
                {
                    return false;
                }

                //判断是否存在文件夹
                string[] directoryNames = GetDirectories(directoryPath);
                if (directoryNames.Length > 0)
                {
                    return false;
                }

                return true;
            }
            catch
            {
                //这里记录日志
                //LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message);
                return true;
            }
        }
        #endregion

        #region 检测指定目录中是否存在指定的文件
        /// <summary>
        /// 检测指定目录中是否存在指定的文件,若要搜索子目录请使用重载方法.
        /// </summary>
        /// <param name="directoryPath">指定目录的绝对路径</param>
        /// <param name="searchPattern">模式字符串，"*"代表0或N个字符，"?"代表1个字符。
        /// 范例："Log*.xml"表示搜索所有以Log开头的Xml文件。</param>        
        public static bool Contains(string directoryPath, string searchPattern)
        {
            try
            {
                if (IsLinux)
                {
                    directoryPath = directoryPath.Replace("\\", "/");
                }
                //获取指定的文件列表
                string[] fileNames = GetFileNames(directoryPath, searchPattern, false);

                //判断指定文件是否存在
                if (fileNames.Length == 0)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
                //LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message);
            }
        }

        /// <summary>
        /// 检测指定目录中是否存在指定的文件
        /// </summary>
        /// <param name="directoryPath">指定目录的绝对路径</param>
        /// <param name="searchPattern">模式字符串，"*"代表0或N个字符，"?"代表1个字符。
        /// 范例："Log*.xml"表示搜索所有以Log开头的Xml文件。</param> 
        /// <param name="isSearchChild">是否搜索子目录</param>
        public static bool Contains(string directoryPath, string searchPattern, bool isSearchChild)
        {
            try
            {
                if (IsLinux)
                {
                    directoryPath = directoryPath.Replace("\\", "/");
                }
                //获取指定的文件列表
                string[] fileNames = GetFileNames(directoryPath, searchPattern, true);

                //判断指定文件是否存在
                if (fileNames.Length == 0)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
                //LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message);
            }
        }
        #endregion

        #region 创建目录
        /// <summary>
        /// 创建目录 不存在才创建
        /// </summary>
        /// <param name="dir">要创建的目录路径包括目录名</param>
        /// <param name="path">文件夹路径 默认使用<see cref="_path"/></param>
        public static void CreateDirectory(string dir, string path = null)
        {
            if (dir.Length == 0)
            {
                return;
            }
            if (path.IsNull())
            {
                path = _path;
            }
            var thisPath = path + "\\" + dir;
            if (IsLinux)
            {
                thisPath = thisPath.Replace("\\", "/");
            }

            if (!Directory.Exists(thisPath))
            {
                Directory.CreateDirectory(thisPath);
            }
        }
        #endregion

        #region 删除目录
        /// <summary>
        /// 删除目录
        /// </summary>
        /// <param name="dir">要删除的目录路径和名称</param>
        /// <param name="path">文件夹路径 默认使用<see cref="_path"/></param>
        public static void DeleteDir(string dir, string path = null)
        {
            if (dir.Length == 0)
            {
                return;
            }
            if (path == null)
            {
                path = _path;
            }
            var thisPath = path + "\\" + dir;
            if (IsLinux)
            {
                thisPath = thisPath.Replace("\\", "/");
            }
            if (Directory.Exists(thisPath))
            {
                Directory.Delete(thisPath);
            }
        }
        #endregion

        #region 删除文件
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="file">要删除的文件路径和名称</param>
        /// <param name="path">文件夹路径 默认使用<see cref="_path"/></param>
        public static void DeleteFile(string file, string path = null)
        {
            if (path.IsNull())
            {
                path = _path;
            }
            var thisPath = path + file;
            if (IsLinux)
            {
                thisPath = thisPath.Replace("\\", "/");
            }
            if (File.Exists(thisPath))
            {
                File.Delete(thisPath);
            }
        }
        #endregion

        #region 创建文件
        /// <summary>
        /// 创建文件
        /// </summary>
        /// <param name="dir">带后缀的文件名</param>
        /// <param name="pagestr">文件内容</param>
        /// <param name="path">文件夹路径 默认使用<see cref="_path"/></param>
        public static void CreateFile(string dir, string pagestr, string path = null)
        {
            if (path.IsNull())
            {
                path = _path;
            }
            else
            {
                CreateDirectory(path);
            }
            dir = dir.Replace("/", "\\");
            if (dir.IndexOf("\\") > -1)
            {
                CreateDirectory(dir.Substring(0, dir.LastIndexOf("\\")));
            }
            var thisPath = path + "\\" + dir;
            if (IsLinux)
            {
                thisPath = thisPath.Replace("\\","/");
            }
            using StreamWriter sw = new StreamWriter(thisPath, false, Encoding.GetEncoding("UTF-8"));
            sw.Write(pagestr);
            sw.Close();
        }
        /// <summary>
        /// 创建文件
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="content">内容</param>
        public static void CreateFileContent(string path, string content)
        {
            FileInfo fi = new FileInfo(path);
            var di = fi.Directory;
            if (!di.Exists)
            {
                di.Create();
            }
            if (IsLinux)
            {
                path = path.Replace("\\", "/");
            }
            using StreamWriter sw = new StreamWriter(path, false, Encoding.GetEncoding("UTF-8"));
            sw.Write(content);
            sw.Close();
        }
        #endregion

        #region 移动文件(剪贴--粘贴)
        /// <summary>
        /// 移动文件(剪贴--粘贴)
        /// </summary>
        /// <param name="dir1">要移动的文件的路径及全名(包括后缀)</param>
        /// <param name="dir2">文件移动到新的位置,并指定新的文件名</param>
        public static void MoveFile(string dir1, string dir2)
        {
            dir1 = dir1.Replace("/", "\\");
            dir2 = dir2.Replace("/", "\\");
          

            var path1 = _path + "\\" + dir1;
            var path2 = _path + "\\" + dir2;
            if (IsLinux)
            {
                path1 = path1.Replace("\\", "/");
                path2 = path2.Replace("\\", "/");
            }
            if (File.Exists(path1))
            {
                File.Move(path1, path2);
            }
        }
        #endregion

        #region 复制文件
        /// <summary>
        /// 复制文件
        /// </summary>
        /// <param name="dir1">要复制的文件的路径已经全名(包括后缀)</param>
        /// <param name="dir2">目标位置,并指定新的文件名</param>
        public static void CopyFile(string dir1, string dir2)
        {
            dir1 = dir1.Replace("/", "\\");
            dir2 = dir2.Replace("/", "\\");

            var path1 = _path + "\\" + dir1;
            var path2 = _path + "\\" + dir2;
            if (IsLinux)
            {
                path1 = path1.Replace("\\", "/");
                path2 = path2.Replace("\\", "/");
            }

            if (File.Exists(path1))
            {
                File.Copy(path1, path2, true);
            }
        }
        #endregion

        #region 根据时间得到目录名 / 格式:yyyyMMdd 或者 HHmmssff

        /// <summary>
        /// 获取系统根节点路径 www文件夹下
        /// </summary>
        /// <param name="folder">文件夹名称</param>
        /// <returns></returns>
        public static string GetSystemRootDirectory(string folder = default)
        {
            var path = $"{SystemConst.SYS_FILE_FOLDER_ROOT}/{folder ?? "Uploads"}/{DateTime.Now:yyyy/MM/dd}";
            CreateDirectory(MapPath(path));
            return path;
        }

        /// <summary>
        /// 获取运行时的文件夹路径 在web上使用
        /// <para>格式 $"/{foleder}/{<see cref="DateTime.Now"/>:yyyy}/{<see cref="DateTime.Now"/>:MM}/<see cref="DateTime.Now"/>:dd/"</para>
        /// </summary>
        /// <param name="folder">文件夹名称</param>
        /// <param name="isDate">根据年月分层</param>
        /// <returns></returns>
        public static string GetDirectory(string folder = default, bool isDate = true)
        {
            var path = $"/{folder ?? "Uploads"}/{DateTime.Now:yyyy}/{DateTime.Now:MM}/{DateTime.Now:dd}/";
            if (!isDate)
            {
                path = $"/{folder ?? "Uploads"}/{DateTime.Now:yyyy-MM-dd}/";
            }
            CreateDirectory(MapPath(path));
            return path;
        }


        /// <summary>
        /// 根据时间得到目录名yyyyMMdd
        /// </summary>
        /// <returns></returns>
        public static string GetDateDir()
        {
            return DateTime.Now.ToString("yyyyMMdd");
        }
        /// <summary>
        /// 根据时间得到文件名HHmmssff
        /// </summary>
        /// <returns></returns>
        public static string GetDateFile()
        {
            return DateTime.Now.ToString("HHmmssff");
        }
        #endregion

        #region 根据时间获取指定路径的 后缀名的 的所有文件
        /// <summary>
        /// 根据时间获取指定路径的 后缀名的 的所有文件
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <param name="Extension">后缀名 比如.txt</param>
        /// <returns></returns>
        public static DataRow[] GetFilesByTime(string path, string Extension)
        {
            if (Directory.Exists(path))
            {
                string fielExts = string.Format("*{0}", Extension);
                string[] files = Directory.GetFiles(path, fielExts);
                if (files.Length > 0)
                {
                    DataTable table = new DataTable();
                    table.Columns.Add(new DataColumn("filename", Type.GetType("System.String")));
                    table.Columns.Add(new DataColumn("createtime", Type.GetType("System.DateTime")));
                    for (int i = 0; i < files.Length; i++)
                    {
                        DataRow row = table.NewRow();
                        DateTime creationTime = File.GetCreationTime(files[i]);
                        string fileName = Path.GetFileName(files[i]);
                        row["filename"] = fileName;
                        row["createtime"] = creationTime;
                        table.Rows.Add(row);
                    }
                    return table.Select(string.Empty, "createtime desc");
                }
            }
            return new DataRow[0];
        }
        #endregion

        #region 复制文件夹
        /// <summary>
        /// 复制文件夹(递归)
        /// </summary>
        /// <param name="varFromDirectory">源文件夹路径</param>
        /// <param name="varToDirectory">目标文件夹路径</param>
        public static void CopyFolder(string varFromDirectory, string varToDirectory)
        {
            Directory.CreateDirectory(varToDirectory);
            if (IsLinux)
            {
                varFromDirectory = varFromDirectory.Replace("\\", "/");
                varToDirectory = varToDirectory.Replace("\\", "/");
            }
            if (!Directory.Exists(varFromDirectory))
            {
                return;
            }

            string[] directories = Directory.GetDirectories(varFromDirectory);

            if (directories.Length > 0)
            {
                foreach (string d in directories)
                {
                    CopyFolder(d, varToDirectory + d.Substring(d.LastIndexOf("\\")));
                }
            }
            string[] files = Directory.GetFiles(varFromDirectory);
            if (files.Length > 0)
            {
                foreach (string s in files)
                {
                    File.Copy(s, varToDirectory + s.Substring(s.LastIndexOf("\\")), true);
                }
            }
        }
        #endregion

        #region 检查文件,如果文件不存在则创建
        /// <summary>
        /// 检查文件,如果文件不存在则创建  
        /// </summary>
        /// <param name="FilePath">路径,包括文件名</param>
        public static void ExistsFile(string FilePath)
        {
            //if(!File.Exists(FilePath))    
            //File.Create(FilePath);    
            //以上写法会报错,详细解释请看下文.........   
            if (IsLinux)
            {
                FilePath = FilePath.Replace("\\", "/");
            }
            if (!File.Exists(FilePath))
            {
                FileStream fs = File.Create(FilePath);
                fs.Close();
            }
        }
        #endregion

        #region 删除指定文件夹对应其他文件夹里的文件
        /// <summary>
        /// 删除指定文件夹对应其他文件夹里的文件
        /// </summary>
        /// <param name="varFromDirectory">指定文件夹路径</param>
        /// <param name="varToDirectory">对应其他文件夹路径</param>
        public static void DeleteFolderFiles(string varFromDirectory, string varToDirectory)
        {
            Directory.CreateDirectory(varToDirectory);
            if (IsLinux)
            {
                varFromDirectory = varFromDirectory.Replace("\\", "/");
                varToDirectory = varToDirectory.Replace("\\", "/");
            }
            if (!Directory.Exists(varFromDirectory))
            {
                return;
            }

            string[] directories = Directory.GetDirectories(varFromDirectory);

            if (directories.Length > 0)
            {
                foreach (string d in directories)
                {
                    DeleteFolderFiles(d, varToDirectory + d.Substring(d.LastIndexOf("\\")));
                }
            }


            string[] files = Directory.GetFiles(varFromDirectory);

            if (files.Length > 0)
            {
                foreach (string s in files)
                {
                    File.Delete(varToDirectory + s.Substring(s.LastIndexOf("\\")));
                }
            }
        }
        #endregion

        #region 从文件的绝对路径中获取文件名( 包含扩展名 )
        /// <summary>
        /// 从文件的绝对路径中获取文件名( 包含扩展名 )
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>        
        public static string GetFileName(string filePath)
        {
            //获取文件的名称
            FileInfo fi = new FileInfo(filePath);
            return fi.Name;
        }

        /// <summary>
        /// 获取文件名
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static string GetFileName(IFormFile file)
        {
            return Guid.NewGuid().ToString() + GetExtension(file.FileName);
        }
        #endregion

        #region 复制文件参考方法,页面中引用
        /// <summary>
        /// 复制文件参考方法,页面中引用
        /// </summary>
        /// <param name="cDir">新路径</param>
        /// <param name="TempId">模板引擎替换编号</param>
        public static void CopyFiles(string cDir, string TempId)
        {
            //if (Directory.Exists(Request.PhysicalApplicationPath + "\\Controls"))
            //{
            //    string TempStr = string.Empty;
            //    StreamWriter sw;
            //    if (File.Exists(Request.PhysicalApplicationPath + "\\Controls\\Default.aspx"))
            //    {
            //        TempStr = File.ReadAllText(Request.PhysicalApplicationPath + "\\Controls\\Default.aspx");
            //        TempStr = TempStr.Replace("{$ChannelId$}", TempId);

            //        sw = new StreamWriter(Request.PhysicalApplicationPath + "\\" + cDir + "\\Default.aspx", false, System.Text.Encoding.GetEncoding("GB2312"));
            //        sw.Write(TempStr);
            //        sw.Close();
            //    }
            //    if (File.Exists(Request.PhysicalApplicationPath + "\\Controls\\Column.aspx"))
            //    {
            //        TempStr = File.ReadAllText(Request.PhysicalApplicationPath + "\\Controls\\Column.aspx");
            //        TempStr = TempStr.Replace("{$ChannelId$}", TempId);

            //        sw = new StreamWriter(Request.PhysicalApplicationPath + "\\" + cDir + "\\List.aspx", false, System.Text.Encoding.GetEncoding("GB2312"));
            //        sw.Write(TempStr);
            //        sw.Close();
            //    }
            //    if (File.Exists(Request.PhysicalApplicationPath + "\\Controls\\Content.aspx"))
            //    {
            //        TempStr = File.ReadAllText(Request.PhysicalApplicationPath + "\\Controls\\Content.aspx");
            //        TempStr = TempStr.Replace("{$ChannelId$}", TempId);

            //        sw = new StreamWriter(Request.PhysicalApplicationPath + "\\" + cDir + "\\View.aspx", false, System.Text.Encoding.GetEncoding("GB2312"));
            //        sw.Write(TempStr);
            //        sw.Close();
            //    }
            //    if (File.Exists(Request.PhysicalApplicationPath + "\\Controls\\MoreDiss.aspx"))
            //    {
            //        TempStr = File.ReadAllText(Request.PhysicalApplicationPath + "\\Controls\\MoreDiss.aspx");
            //        TempStr = TempStr.Replace("{$ChannelId$}", TempId);

            //        sw = new StreamWriter(Request.PhysicalApplicationPath + "\\" + cDir + "\\DissList.aspx", false, System.Text.Encoding.GetEncoding("GB2312"));
            //        sw.Write(TempStr);
            //        sw.Close();
            //    }
            //    if (File.Exists(Request.PhysicalApplicationPath + "\\Controls\\ShowDiss.aspx"))
            //    {
            //        TempStr = File.ReadAllText(Request.PhysicalApplicationPath + "\\Controls\\ShowDiss.aspx");
            //        TempStr = TempStr.Replace("{$ChannelId$}", TempId);

            //        sw = new StreamWriter(Request.PhysicalApplicationPath + "\\" + cDir + "\\Diss.aspx", false, System.Text.Encoding.GetEncoding("GB2312"));
            //        sw.Write(TempStr);
            //        sw.Close();
            //    }
            //    if (File.Exists(Request.PhysicalApplicationPath + "\\Controls\\Review.aspx"))
            //    {
            //        TempStr = File.ReadAllText(Request.PhysicalApplicationPath + "\\Controls\\Review.aspx");
            //        TempStr = TempStr.Replace("{$ChannelId$}", TempId);

            //        sw = new StreamWriter(Request.PhysicalApplicationPath + "\\" + cDir + "\\Review.aspx", false, System.Text.Encoding.GetEncoding("GB2312"));
            //        sw.Write(TempStr);
            //        sw.Close();
            //    }
            //    if (File.Exists(Request.PhysicalApplicationPath + "\\Controls\\Search.aspx"))
            //    {
            //        TempStr = File.ReadAllText(Request.PhysicalApplicationPath + "\\Controls\\Search.aspx");
            //        TempStr = TempStr.Replace("{$ChannelId$}", TempId);

            //        sw = new StreamWriter(Request.PhysicalApplicationPath + "\\" + cDir + "\\Search.aspx", false, System.Text.Encoding.GetEncoding("GB2312"));
            //        sw.Write(TempStr);
            //        sw.Close();
            //    }
            //}
        }
        #endregion

        #region 创建一个目录
        /// <summary>
        /// 创建一个目录  绝对路径
        /// </summary>
        /// <param name="directoryPath">目录的绝对路径</param>
        public static void CreateDirectory(string directoryPath)
        {
            if (IsLinux)
            {
                directoryPath = directoryPath.Replace("\\", "/");
            }
            //如果目录不存在则创建该目录
            if (!IsExistDirectory(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }
        }
        #endregion

        #region 创建一个文件

        /// <summary>
        /// 创建文件 在web服务下使用
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static string CreateFile(IFormFile file)
        {
            var fileName = GetFileName(file);

            var folder = GetDirectory();

            var filePath = Path.Combine(folder, fileName);
            var path = filePath.ToLocalBinDirectory();
            if (IsLinux)
            {
                path = path.Replace("\\", "/");
            }
            using (FileStream fs = File.Create(path))
            {
                file.CopyTo(fs);
                fs.Flush();
                return filePath;
            }
        }


        /// <summary>
        /// 创建一个文件。
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>
        public static void CreateFile(string filePath)
        {
            try
            {
                if (IsLinux)
                {
                    filePath = filePath.Replace("\\", "/");
                }
                //如果文件不存在则创建该文件
                if (!IsExistFile(filePath))
                {
                    //创建一个FileInfo对象
                    FileInfo file = new FileInfo(filePath);

                    //创建文件
                    FileStream fs = file.Create();

                    //关闭文件流
                    fs.Close();
                }
            }
            catch (Exception ex)
            {
                //LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message);
                throw;
            }
        }

        /// <summary>
        /// 创建一个文件,并将字节流写入文件。
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>
        /// <param name="buffer">二进制流数据</param>
        public static void CreateFile(string filePath, byte[] buffer)
        {
            try
            {
                if (IsLinux)
                {
                    filePath = filePath.Replace("\\", "/");
                }
                //如果文件不存在则创建该文件
                if (!IsExistFile(filePath))
                {
                    //创建一个FileInfo对象
                    FileInfo file = new FileInfo(filePath);

                    //创建文件
                    FileStream fs = file.Create();

                    //写入二进制流
                    fs.Write(buffer, 0, buffer.Length);

                    //关闭文件流
                    fs.Close();
                }
            }
            catch (Exception ex)
            {
                //LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message);
                throw;
            }
        }
        #endregion

        #region 获取文本文件的行数
        /// <summary>
        /// 获取文本文件的行数
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>        
        public static int GetLineCount(string filePath)
        {
            if (IsLinux)
            {
                filePath = filePath.Replace("\\", "/");
            }
            //将文本文件的各行读到一个字符串数组中
            string[] rows = File.ReadAllLines(filePath);

            //返回行数
            return rows.Length;
        }
        #endregion

        #region 获取一个文件的长度
        /// <summary>
        /// 获取一个文件的长度,单位为Byte
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>        
        public static long GetFileSize(string filePath)
        {
            if (IsLinux)
            {
                filePath = filePath.Replace("\\", "/");
            }
            //创建一个文件对象
            FileInfo fi = new FileInfo(filePath);

            //获取文件的大小
            return fi.Length;
        }
        #endregion

        #region 获取文件大小并以B，KB，GB，TB
        /// <summary>
        /// 计算文件大小函数(保留两位小数),Size为字节大小
        /// </summary>
        /// <param name="size">初始文件大小</param>
        /// <returns></returns>
        public static string ToFileSize(long size)
        {
            string m_strSize = "";
            long FactSize = 0;
            FactSize = size;
            if (FactSize < 1024.00)
            {
                m_strSize = FactSize.ToString("F2") + " 字节";
            }
            else if (FactSize >= 1024.00 && FactSize < 1048576)
            {
                m_strSize = (FactSize / 1024.00).ToString("F2") + " KB";
            }
            else if (FactSize >= 1048576 && FactSize < 1073741824)
            {
                m_strSize = (FactSize / 1024.00 / 1024.00).ToString("F2") + " MB";
            }
            else if (FactSize >= 1073741824)
            {
                m_strSize = (FactSize / 1024.00 / 1024.00 / 1024.00).ToString("F2") + " GB";
            }

            return m_strSize;
        }
        #endregion

        #region 获取指定目录中的子目录列表
        /// <summary>
        /// 获取指定目录及子目录中所有子目录列表
        /// </summary>
        /// <param name="directoryPath">指定目录的绝对路径</param>
        /// <param name="searchPattern">模式字符串，"*"代表0或N个字符，"?"代表1个字符。
        /// 范例："Log*.xml"表示搜索所有以Log开头的Xml文件。</param>
        /// <param name="isSearchChild">是否搜索子目录</param>
        public static string[] GetDirectories(string directoryPath, string searchPattern, bool isSearchChild)
        {
            try
            {
                if (IsLinux)
                {
                    directoryPath = directoryPath.Replace("\\", "/");
                }
                if (isSearchChild)
                {
                    return Directory.GetDirectories(directoryPath, searchPattern, SearchOption.AllDirectories);
                }
                else
                {
                    return Directory.GetDirectories(directoryPath, searchPattern, SearchOption.TopDirectoryOnly);
                }
            }
            catch (IOException ex)
            {
                throw;
            }
        }
        #endregion

        #region 向文本文件写入内容

        /// <summary>
        /// 向文本文件中写入内容
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>
        /// <param name="text">写入的内容</param>
        /// <param name="encoding">编码</param>
        public static void WriteText(string filePath, string text, Encoding encoding)
        {
            if (IsLinux)
            {
                filePath = filePath.Replace("\\", "/");
            }
            //向文件写入内容
            File.WriteAllText(filePath, text, encoding);
        }
        #endregion

        #region 向文本文件的尾部追加内容
        /// <summary>
        /// 向文本文件的尾部追加内容
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>
        /// <param name="content">写入的内容</param>
        public static void AppendText(string filePath, string content)
        {
            if (IsLinux)
            {
                filePath = filePath.Replace("\\", "/");
            }
            File.AppendAllText(filePath, content);
        }
        #endregion

        #region 将现有文件的内容复制到新文件中
        /// <summary>
        /// 将源文件的内容复制到目标文件中
        /// </summary>
        /// <param name="sourceFilePath">源文件的绝对路径</param>
        /// <param name="destFilePath">目标文件的绝对路径</param>
        public static void Copy(string sourceFilePath, string destFilePath)
        {
            if (IsLinux)
            {
                sourceFilePath = sourceFilePath.Replace("\\", "/");
                destFilePath = destFilePath.Replace("\\", "/");
            }
            File.Copy(sourceFilePath, destFilePath, true);
        }
        #endregion

        #region 将文件移动到指定目录
        /// <summary>
        /// 将文件移动到指定目录
        /// </summary>
        /// <param name="sourceFilePath">需要移动的源文件的绝对路径</param>
        /// <param name="descDirectoryPath">移动到的目录的绝对路径</param>
        public static void Move(string sourceFilePath, string descDirectoryPath)
        {
            //获取源文件的名称
            string sourceFileName = GetFileName(sourceFilePath);


            var path = descDirectoryPath + "\\" + sourceFileName;
            if (IsLinux)
            {
                path = path.Replace("\\", "/");
            }

            if (IsExistDirectory(descDirectoryPath))
            {
                //如果目标中存在同名文件,则删除
                if (IsExistFile(path))
                {
                    DeleteFile(path);
                }
                //将文件移动到指定目录
                File.Move(sourceFilePath, path);
            }
        }
        #endregion

        #region 从文件的绝对路径中获取文件名( 不包含扩展名 )
        /// <summary>
        /// 从文件的绝对路径中获取文件名( 不包含扩展名 )
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>        
        public static string GetFileNameNoExtension(string filePath)
        {
            if (IsLinux)
            {
                filePath = filePath.Replace("\\", "/");
            }
            //获取文件的名称
            FileInfo fi = new FileInfo(filePath);
            return fi.Name.Split('.')[0];
        }
        #endregion

        #region 从文件的绝对路径中获取扩展名
        /// <summary>
        /// 从文件的绝对路径中获取扩展名
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>        
        public static string GetExtension(string filePath)
        {
            if (IsLinux)
            {
                filePath = filePath.Replace("\\", "/");
            }
            //获取文件的名称
            FileInfo fi = new FileInfo(filePath);
            return fi.Extension;
        }
        #endregion

        #region 清空指定目录
        /// <summary>
        /// 清空指定目录下所有文件及子目录,但该目录依然保存.
        /// </summary>
        /// <param name="directoryPath">指定目录的相对路径</param>
        public static void ClearDirectory(string directoryPath)
        {

            directoryPath = directoryPath.ToLocalBinDirectory();
            if (IsLinux)
            {
                directoryPath = directoryPath.Replace("\\", "/");
            }
            if (IsExistDirectory(directoryPath))
            {
                //删除目录中所有的文件
                string[] fileNames = GetFileNames(directoryPath);
                for (int i = 0; i < fileNames.Length; i++)
                {
                    DeleteFile(fileNames[i]);
                }
                //删除目录中所有的子目录
                string[] directoryNames = GetDirectories(directoryPath);
                for (int i = 0; i < directoryNames.Length; i++)
                {
                    DeleteDirectory(directoryNames[i]);
                }
            }
        }
        #endregion

        #region 清空文件内容
        /// <summary>
        /// 清空文件内容
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>
        public static void ClearFile(string filePath)
        {
            if (IsLinux)
            {
                filePath = filePath.Replace("\\", "/");
            }

            //删除文件
            File.Delete(filePath);

            //重新创建该文件
            CreateFile(filePath);
        }
        #endregion

        #region 删除指定目录
        /// <summary>
        /// 删除指定目录及其所有子目录
        /// </summary>
        /// <param name="directoryPath">指定目录的相对路径</param>
        public static void DeleteDirectory(string directoryPath)
        {
            directoryPath = directoryPath.ToLocalBinDirectory();
            if (IsLinux)
            {
                directoryPath = directoryPath.Replace("\\", "/");
            }
            if (IsExistDirectory(directoryPath))
            {
                Directory.Delete(directoryPath, true);
            }
        }
        #endregion

        #region 本地路径

#pragma warning disable CS1574 // XML 注释中有无法解析的 cref 特性
        /// <summary>
        /// 本地路径  <see cref="AppDomain.CurrentDomain.BaseDirectory"/>
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string MapPath(string path)
#pragma warning restore CS1574 // XML 注释中有无法解析的 cref 特性
        {
            var thisPath = path.ToLocalBinDirectory();

            if (IsLinux)
            {
                thisPath = thisPath.Replace("\\", "/");
            }
            return thisPath;
        }
        #endregion


        #region 下载文件
        private static HttpClient _httpClient = null;
        /// <summary>
        /// 下载并保存
        /// </summary>
        /// <param name="url">网络路径</param>
        /// <param name="savePath">保存本地的文件夹</param>
        /// <param name="suffix">文件夹后缀</param>
        /// <param name="isYear">是否根据年月日创建文件夹 路径/2021/03/18</param>
        /// <returns>文件路径</returns>
        public static string FileDownSave(string url, string savePath, bool isYear = true, string suffix = null)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new FileLoadException("网络路径为空");
            }
            if (suffix == null)
            {
                suffix = url.Split('.')[1];
            }
            if (isYear)
            {
                savePath = GetDirectory(savePath);
            }
            CreateDirectory(savePath);
            var path = $"{savePath}/{Guid.NewGuid()}.{suffix}";

            if (IsLinux)
            {
                path = path.Replace("\\", "/");
            }
            if (_httpClient == null)
            {
                _httpClient = new HttpClient();
            }
            var t = _httpClient.GetByteArrayAsync(url);
            t.Wait();
            using Stream responseStream = new MemoryStream(t.Result);
            using Stream stream = new FileStream(path, FileMode.Create);
            byte[] bArr = new byte[1024];
            int size = responseStream.Read(bArr, 0, bArr.Length);
            while (size > 0)
            {
                stream.Write(bArr, 0, size);
                size = responseStream.Read(bArr, 0, bArr.Length);
            }
            stream.Close();
            responseStream.Close();
            return path;
        }
        /// <summary>
        /// 下载并保存
        /// </summary>
        /// <param name="url">网络路径</param>
        /// <param name="savePath">保存本地的文件夹</param>
        /// <returns>文件路径</returns>
        public static void FileDownSave(string url, string savePath)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new FileLoadException("网络路径为空");
            }
            if (_httpClient == null)
            {
                _httpClient = new HttpClient();
            }
            var t = _httpClient.GetByteArrayAsync(url);
            t.Wait();
            using Stream responseStream = new MemoryStream(t.Result);
            var path = _path + "/" + savePath;
            if (IsLinux)
            {
                path = path.Replace("\\", "/");
            }
            using Stream stream = new FileStream(path, FileMode.Create);
            byte[] bArr = new byte[1024];
            int size = responseStream.Read(bArr, 0, bArr.Length);
            while (size > 0)
            {
                stream.Write(bArr, 0, size);
                size = responseStream.Read(bArr, 0, bArr.Length);
            }
            stream.Close();
            responseStream.Close();
        }
        #endregion

        /// <summary>
        /// 获取文件后缀
        /// </summary>
        /// <param name="url">url路径 例如12312312.jpg</param>
        /// <returns>.文件后缀名 例如: .jpg</returns>
        public static string GetFileSuffix(string url)
        {
            if (string.IsNullOrEmpty(url))
            {
                return url;
            }
            /*
            string filename  = Path.GetFileName(fullPath);//返回带扩展名的文件名 "default.avi"
            string extension = Path.GetExtension(fullPath);//扩展名 ".aspx"
            string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fullPath);// 没有扩展名的文件名 "default"


            string dirPath = Path.GetDirectoryName(filePath) //返回文件所在目录 "d:\test"
            string fullPath1 = Path.Combine(@"d:\test", "default.avi")  //返回 "d:\test\default.avi"

            string fullPath2 = Path.GetFullPath("config.ini");//返回指定路径字符串的绝对路径
             */
            return Path.GetExtension(url);
        }
    }
}
